<template>
  <span
    v-show="cd.seconds"
    class="count-down"
  >
    <slot :cd="cd" />
  </span>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  props: {
    diffTime: {
      type: Number,
      default: 0,
    },
    // 默认倒计间隔，单位s
    intervalTime: {
      type: Number,
      default: 1,
    },
  },
  data () {
    return {
      cd: {
        day: 0,
        hour: 0,
        hours: 0,
        minute: 0,
        minutes: 0,
        second: 0,
        seconds: 0,
      },
      timer: 0,
      showFlag: false,
      endTime: 0,
    }
  },
  watch: {
    diffTime (newVal) {
      this.endTime = Date.now() + this.diffTime
      console.log('剩余xxxx', newVal)
      this.clearTimer()
      this.startCount(newVal)
    },
  },
  created () {
    if (this.diffTime) {
      this.endTime = Date.now() + this.diffTime
    }
    this.startCount(this.endTime)
  },
  beforeDestroy () {
    console.log('beforeDestroy CountDown')
    this.clearTimer()
  },
  methods: {
    startCount (targetTime: number) {
      if (this.endTime > Date.now()) {
        this.countDown(targetTime)
        this.timer = window.setInterval(this.countDown.bind(this, targetTime),
          this.intervalTime * 500)
      } else {
        this.$emit('timeEnded', false)
      }
    },
    clearTimer () {
      window.clearInterval(this.timer)
    },
    countDown (targetTime: number) {
      const now = Date.now()
      const diff = targetTime - now
      if (diff > 0) {
        const seconds = Math.floor((targetTime - now) / 1000)
        const second = seconds % 60
        const minutes = Math.floor(seconds / 60)
        const minute = minutes % 60
        const hours = Math.floor(minutes / 60)
        const hour = hours % 24
        const days = Math.floor(hours / 24)
        this.$set(this.$data, 'cd', {
          day: days,
          hour,
          hours,
          minute,
          minutes,
          second,
          seconds,
        })
      } else {
        // this.showFlag = false
        this.clearTimer()
        this.$emit('timeEnded', true)
      }
    },
  },
})
</script>
